<template>
    <div class="data-model-container">
        <div class="header">
            <a-button type="primary" @click="handleAdd">+ 新建</a-button>
            <a-button @click="handleRefresh">刷新</a-button>
        </div>

        <a-table :columns="columns" :dataSource="dataList" :pagination="false" rowKey="uuid">
            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'operation'">
                    <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                    <a-divider type="vertical" />
                    <a-popconfirm title="确定要删除这条数据吗?" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record)">
                        <a-button type="link" danger>删除</a-button>
                    </a-popconfirm>
                </template>
            </template>
        </a-table>

        <!-- 新增/编辑模态框 -->
        <a-modal v-model:open="modalVisible" :title="isEdit ? '编辑数据模型' : '添加'" width="600px" @ok="handleModalOk"
            @cancel="handleModalCancel">
            <a-form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="数据名称" name="name" required>
                    <a-input v-model:value="formState.name" />
                </a-form-item>

                <a-form-item label="数据类型" name="DataType" required>
                    <a-select v-model:value="formState.DataType" @change="handleDataTypeChange">
                        <a-select-option :value="1">整数型</a-select-option>
                        <a-select-option :value="2">字符型</a-select-option>
                        <a-select-option :value="3">浮点型</a-select-option>
                        <a-select-option :value="4">JSON</a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="设备模型" name="DataDeviceType" required>
                    <a-select v-model:value="formState.DataDeviceType" :disabled="isEdit">
                        <a-select-option v-for="option in deviceModelOptions" :key="option.ID" :value="option.type">
                            {{ option.dec }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="默认值" name="DataDefaultValue" required>
                    <a-input v-model:value="formState.DataDefaultValue" />
                </a-form-item>

                <a-form-item label="是否告警" name="dataAlarm" required>
                    <a-radio-group v-model:value="formState.dataAlarm">
                        <a-radio :value="1">是</a-radio>
                        <a-radio :value="0">否</a-radio>
                    </a-radio-group>
                </a-form-item>

                <template v-if="formState.dataAlarm === 1">
                    <a-form-item label="告警等级" name="AlarmLevel" required>
                        <a-select v-model:value="formState.AlarmLevel">
                            <a-select-option :value="0">提示</a-select-option>
                            <a-select-option :value="1">次要</a-select-option>
                            <a-select-option :value="2">重要</a-select-option>
                            <a-select-option :value="3">紧急</a-select-option>
                            <a-select-option :value="4">致命</a-select-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item label="告警显示信息" name="AlarmMessage" required>
                        <a-input v-model:value="formState.AlarmMessage" />
                    </a-form-item>

                    <a-form-item label="消除显示信息" name="AlarmClearMessage">
                        <a-input v-model:value="formState.AlarmClearMessage" />
                    </a-form-item>
                </template>
                <template v-else>
                    <a-form-item label="是否存储" name="dataRecord" required>
                        <a-radio-group v-model:value="formState.dataRecord" @change="handleStorageChange">
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="0">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </template>

                <template v-if="formState.dataRecord === 1">
                    <a-form-item label="存储方式" name="RecordType" required>
                        <a-select v-model:value="formState.RecordType">
                            <a-select-option :value="1">定时存储</a-select-option>
                            <a-select-option :value="0">变化存储</a-select-option>
                            <a-select-option :value="2">即时存储</a-select-option>
                            <a-select-option :value="3">变化百分比</a-select-option>
                        </a-select>
                    </a-form-item>

                    <template v-if="formState.RecordType === 3">
                        <a-form-item label="百分比(%)" name="RecordDataCharge" required>
                            <a-input v-model:value="formState.RecordDataCharge" />
                        </a-form-item>
                    </template>

                    <template v-else-if="formState.RecordType === 1">
                        <a-form-item label="存储间隔(单位:秒)" name="recordInterval">
                            <a-input v-model:value="formState.recordInterval" />
                        </a-form-item>
                    </template>
                    <template v-else-if="formState.RecordType === 0">
                        <a-form-item label="变化值" name="RecordDataCharge" required>
                            <a-input v-model:value="formState.RecordDataCharge" />
                        </a-form-item>
                    </template>
                </template>

                <a-form-item label="单位" name="DataUnit">
                    <a-input v-model:value="formState.DataUnit" />
                </a-form-item>

                <template v-if="!isEdit">
                    <a-form-item label="添加数量" name="Count" required>
                        <a-input v-model:value="formState.Count" />
                    </a-form-item>
                </template>

                <a-form-item label="描述" name="DataDescription" required>
                    <a-textarea v-model:value="formState.DataDescription" :rows="3" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import { cvaiApi } from '/@/api/system/cvai-api';

// 表格列定义
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
    },
    {
        title: '数据名称',
        dataIndex: 'name',
        key: 'name'
    },
    {
        title: '设备模型',
        dataIndex: 'DataDeviceType',
        key: 'DataDeviceType',
        customRender: ({ text }) => {
            const deviceMap = Object.fromEntries(deviceModelOptions.value.map(item => [item.type, item.dec]));
            return deviceMap[text] || text;
        }
    },
    {
        title: '数据类型',
        dataIndex: 'DataType',
        key: 'DataType',
        customRender: ({ text }) => {
            const typeMap = {
                1: '整数型',
                2: '字符型',
                3: '浮点型',
                4: 'JSON'
            };
            return typeMap[text] || text;
        }
    },
    {
        title: '单位',
        dataIndex: 'DataUnit',
        key: 'DataUnit'
    },
    {
        title: '默认值',
        dataIndex: 'DataDefaultValue',
        key: 'DataDefaultValue'
    },
    {
        title: '操作',
        key: 'operation',
        width: 200
    }
];

// 数据列表
const dataList = ref([]);
const modalVisible = ref(false);
const isEdit = ref(false);
const currentId = ref('');
const formRef = ref();

//组态模型options
const deviceModelOptions = ref([]);
function getDisplayModelListOptions() {
    cvaiApi.supportDevice({ type: 1 }).then((res) => {
        deviceModelOptions.value = res.list;
    });
}

// 表单初始状态
const initFormState = {
    name: '',
    DataType: 1, // 默认整数
    DataDeviceType: 470, // 默认环保HJ212-2017
    DataDefaultValue: '',
    dataAlarm: 0, // 默认不告警
    AlarmLevel: '提示',
    AlarmMessage: '',
    AlarmClearMessage: '',
    dataRecord: 0, // 默认存储
    RecordType: 0, // 默认变化存储,
    RecordDataCharge: '',
    DataUnit: '',
    Count: 1,
    DataDescription: ''
};

const formState = reactive({ ...initFormState });

// 获取数据列表
const fetchDataList = async () => {
    try {
        cvaiApi.GetStaticDataList({ type: 1 }).then((res) => {
            dataList.value = res.list;
        });
    } catch (error) {
        message.error('获取数据列表失败');
        console.error(error);
    }
};

// 新增数据
const handleAdd = () => {
    // 重置表单
    Object.assign(formState, initFormState);
    isEdit.value = false;
    modalVisible.value = true;
};

// 编辑数据
const handleEdit = async (record) => {
    try {
        Object.keys(formState).forEach(key => {
            if (record.hasOwnProperty(key)) {
                formState[key] = record[key];
            }
        });
        currentId.value = record.uuid;
        isEdit.value = true;
        modalVisible.value = true;
    } catch (error) {
        console.error(error);
    }
};

// 删除数据
const handleDelete = async (record) => {
    try {
        cvaiApi.DelStaticData({ uuid: record.uuid }).then((res) => {
            if (res.code == 0) {
                message.success('删除成功');
                fetchDataList();
            } else {
                message.error('删除失败');
            }
        });
    } catch (error) {
        message.error('删除失败');
        console.error(error);
    }
};

// 刷新数据
const handleRefresh = () => {
    fetchDataList();
};

// 数据类型变化处理
const handleDataTypeChange = (value) => {
    // 可以根据不同类型设置不同的默认值
    if (value === 1 || value === 3) {
        formState.DataDefaultValue = '0';
    } else if (value === 2) {
        formState.DataDefaultValue = '';
    } else if (value === 4) {
        formState.DataDefaultValue = '{}';
    }
};

// 存储方式变化处理
const handleStorageChange = (e) => {
    if (e.target.value === 0) {
        formState.RecordType = '';
    }
};
// 模态框确定
const handleModalOk = async () => {
    try {
        // 编辑
        if (isEdit.value) {
            //移除对象formFormState中Count属性以及为空的属性
            Object.keys(formState).forEach(key => {
                if (formState[key] === '' || formState[key] === null || formState[key] === undefined) {
                    delete formState[key];
                }
                //如果formState.dataRecord为1，移除formState.RecordType属性
                if (formState.dataRecord === 1 && formState.RecordType === '') {
                    delete formState.RecordType;
                }
            });
            cvaiApi.EditStaticData({ uuid: currentId.value, Data: formState }).then((res) => {
                if (res.code === 0) {
                    message.success('编辑成功');
                } else {
                    message.error('编辑失败');
                }
                fetchDataList();
            });
        } else {
            // 新增
            cvaiApi.AddStaticData(formState).then((res) => {
                if (res.code === 0) {
                    message.success('新增成功');
                } else {
                    message.error('新增失败');
                }
                fetchDataList();
            });
        }

        modalVisible.value = false;
        fetchDataList();
    } catch (error) {
        message.error(isEdit.value ? '编辑失败' : '新增失败');
        console.error(error);
    }
};

// 模态框取消
const handleModalCancel = () => {
    modalVisible.value = false;
};

// 初始化加载数据
onMounted(() => {
    fetchDataList();
    getDisplayModelListOptions()
});
</script>

<style scoped>
.data-model-container {
    padding: 20px;
    background: #fff;
}

.header {
    margin-bottom: 16px;
}

.header button {
    margin-right: 8px;
}
</style>